package com.estar.assistsurvy.activity;

import java.util.List;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.estar.assistsurvy.R;
import com.estar.assistsurvy.entity.EsLocationInfo;
import com.estar.assistsurvy.entity.EsUserInfo;
import com.estar.assistsurvy.entity.GrabLocationList;
import com.estar.assistsurvy.entity.RequestGrabLocation;
import com.estar.assistsurvy.entity.RequestReBroadcast;
import com.estar.assistsurvy.entity.RequestcaseCancel;
import com.estar.assistsurvy.entity.ResponseGrabLocation;
import com.estar.assistsurvy.entity.ResponseMsg;
import com.estar.assistsurvy.entity.grabPersonLocation;
import com.estar.assistsurvy.thread.CaseCancelThread;
import com.estar.assistsurvy.thread.CaseStopThread;
import com.estar.assistsurvy.thread.GetGrabLocation;
import com.estar.assistsurvy.thread.ReBroadcastThread;
import com.estar.assistsurvy.entity.grabList;
import com.estar.assistsurvy.utils.DrivingRouteOverlay;
import com.estar.assistsurvy.utils.ExitUtils;
import com.estar.assistsurvy.utils.MightypleUtil;
import com.estar.assistsurvy.utils.TimeUtils;
import com.estar.assistsurvy.utils.VoiceUtil;
import com.estar.assistsurvy.widget.TaskOperationPopwindow;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class OrderDetailActivity extends BaseActivity implements OnClickListener,OnGetGeoCoderResultListener,OnGetRoutePlanResultListener,OnMarkerClickListener{

	private RelativeLayout taskDetail;
	private TextView carNum,orderTime,startPoint,endPoint;
	private LinearLayout returnBack;
	private ImageView order_icon;

	private MapView mMapView;
	private BaiduMap mBaidumap;
	private RoutePlanSearch mSearch;
	private Marker marker;
	@SuppressWarnings("unused")
	private RouteLine<?> route;
	private DrivingRouteResult nowResultd  = null;
	private Intent intent;
	private grabList order;
	//	private EsLocationInfo locationInfo;
	private grabPersonLocation PersonLocation;
	private EsLocationInfo LocationInfo;
	private EsUserInfo userInfo;
	private GeoCoder geoCoder;
	private int caseState;
	private TaskOperationPopwindow taskPop;
	private String uuid,deviceId;
	private SharedPreferences preference;
	private ResponseMsg message;
	private ProgressDialog progressdialog;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(progressdialog!=null){
				progressdialog.dismiss();
			}
			switch (msg.what) {
			case -1:
				showShortToast((String) msg.obj);
				break;

			case 0:
				message=new ResponseMsg();
				message=(ResponseMsg) msg.obj;
				if(message.getCode().equals("2")){
					ExitUtils.Unlogin(OrderDetailActivity.this, message.getMessages());
					return;
				}
				showShortToast(message.getMessages());
				break;

			case 1:
				ResponseGrabLocation grabLoc=new ResponseGrabLocation();
				grabLoc=(ResponseGrabLocation) msg.obj;
				if(grabLoc.getCode().equals("1")){
					if(grabLoc.getEsLocationInfo()!=null){
						LocationInfo=grabLoc.getEsLocationInfo();
						setGrabMarker();
					}
				}else if(grabLoc.getCode().equals("0")){
					showShortToast(grabLoc.getMessages());
				}else if(grabLoc.getCode().equals("2")){
					ExitUtils.Unlogin(OrderDetailActivity.this, message.getMessages());
				}
				break;

			case 2:
				ResponseMsg message=new ResponseMsg();
				message=(ResponseMsg) msg.obj;
				if(message.getCode().equals("2")){
					ExitUtils.Unlogin(OrderDetailActivity.this, message.getMessages());
					return;
				}
				showShortToast(message.getMessages());
				break;

			default:
				break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_orderdetail);
		initView();
	}

	private void initView(){
		taskDetail=find(R.id.taskDetail);
		taskDetail.setOnClickListener(this);
		returnBack=find(R.id.returnBack);
		returnBack.setOnClickListener(this);
		carNum=find(R.id.carNum);
		order_icon=find(R.id.order_icon);
		orderTime=find(R.id.orderTime);
		startPoint=find(R.id.startPoint);
		endPoint=find(R.id.endPoint);
		preference=getSharedPreferences("user", Context.MODE_PRIVATE);
		uuid=preference.getString("uuid", "");
		deviceId=MightypleUtil.getDeviceId(OrderDetailActivity.this);

		mMapView = (MapView) findViewById(R.id.mMapView);
		mBaidumap = mMapView.getMap();
		mBaidumap.setOnMarkerClickListener(this);
		mMapView.removeViewAt(1); // 去掉百度logo
		//		mBaidumap.setMaxAndMinZoomLevel(18, 17); //地图的最大最小缩放比例3-18
		mSearch = RoutePlanSearch.newInstance();
		mSearch.setOnGetRoutePlanResultListener(this);
		geoCoder=GeoCoder.newInstance();
		geoCoder.setOnGetGeoCodeResultListener(this);

		intent=getIntent();
		order=(grabList) intent.getExtras().get("order");
		carNum.setText(order.getTargetCar());
//		orderTime.setText(order.getCreateTime());
		orderTime.setText(TimeUtils.EnglishToChinese(order.getUpdateTime()));
		startPoint.setText(order.getGrabPlace());
		endPoint.setText(order.getOccurPlace());
		caseState=Integer.parseInt(order.getCaseState());

		SharedPreferences prefer=getSharedPreferences("location", Context.MODE_PRIVATE);
		String adress=prefer.getString("adress", "");
		String Poi=prefer.getString("Poi", "");
		String currentLocation=null;
		if(Poi.equals("")){
			currentLocation=adress;
		}else{
			currentLocation=Poi;
		}
		switch (caseState) {
		case 1://未抢单
			order_icon.setImageResource(R.drawable.icon_001);
			startPoint.setText(currentLocation);
			PersonLocation=(grabPersonLocation) intent.getExtras().get("location");
			Log.i("wl", "任务详情页面--》"+PersonLocation.getCode());
			if(PersonLocation.getCode().equals("1")){
				List<GrabLocationList> grabLocationList=PersonLocation.getGrabLocationList();
				for(int i=0;i<grabLocationList.size();i++){
					LocationInfo=grabLocationList.get(i).getEsLocationInfo();
					userInfo=grabLocationList.get(i).getEsUserInfo();
					if(LocationInfo!=null){
						setOtherPoint();
//						setGrabMarker();					
//						new MyInfoWindow(OrderDetailActivity.this, mBaidumap, PersonLocation.getGrabLocationList().get(i)).showLocation(marker);
					}
					//					setOtherPoint();
				}
			}
			break;

		case 2://抢单终止
			order_icon.setImageResource(R.drawable.icon_002);
			taskDetail.setVisibility(View.GONE);
			break;

		case 3://已抢单
			order_icon.setImageResource(R.drawable.icon_scrambled);
			taskDetail.setVisibility(View.GONE);
			searchLines();
			runnable.run();
			break;

		case 4://放弃抢单
			order_icon.setImageResource(R.drawable.certification01);
			taskDetail.setVisibility(View.GONE);
			break;

		case 5://注销
			order_icon.setImageResource(R.drawable.icon_003);
			taskDetail.setVisibility(View.GONE);
			break;

		case 6://已完成
			order_icon.setImageResource(R.drawable.icon_004);
			taskDetail.setVisibility(View.GONE);
			break;

		default:
			break;
		}
		if(!order.getLatitude().equals("undefined")&&!order.getLongitude().equals("undefined")){
			setTargetPoint();
		}

		//		LatLng startpt=new LatLng(39.648593, 116.434307);
		//		geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(startpt));
	}
	//设置事发地定位图标
	private void setTargetPoint(){
		//定义Maker坐标点  

		float latitude=Float.parseFloat(order.getLatitude());
		float longitude=Float.parseFloat(order.getLongitude());
		LatLng point = new LatLng(latitude, longitude);  
		//构建Marker图标  
		BitmapDescriptor bitmap = BitmapDescriptorFactory  
				.fromResource(R.drawable.icon_en);  
		//构建MarkerOption，用于在地图上添加Marker  
		OverlayOptions option = new MarkerOptions()  
				.position(point)  
				.icon(bitmap);  
		//在地图上添加Marker，并显示  
		mBaidumap.addOverlay(option);
	}
	//设置其他查勘员定位图标
	private void setOtherPoint(){
		//定义Maker坐标点  
		float latitude=Float.parseFloat(LocationInfo.getLatitude());
		float longitude=Float.parseFloat(LocationInfo.getLongitude());
		LatLng point = new LatLng(latitude, longitude);  
		Bundle bundle=new Bundle();
		bundle.putSerializable("userInfo", userInfo);
		//构建Marker图标  
		BitmapDescriptor bitmap = BitmapDescriptorFactory  
				.fromResource(R.drawable.icon_gcoding);  
		//构建MarkerOption，用于在地图上添加Marker  
		OverlayOptions option = new MarkerOptions()  
				.position(point)  
				.extraInfo(bundle)
				.icon(bitmap);  
		//在地图上添加Marker，并显示  
		mBaidumap.addOverlay(option);
	}

	private void setGrabMarker(){
		//定义Maker坐标点  
		Double latitude=Double.parseDouble(LocationInfo.getLatitude());
		Double longitude=Double.parseDouble(LocationInfo.getLongitude());
		LatLng point = new LatLng(latitude, longitude);  
		//构建Marker图标  
		BitmapDescriptor bitmap = BitmapDescriptorFactory  
				.fromResource(R.drawable.icon_gcoding);  
		//构建MarkerOption，用于在地图上添加Marker  
		MarkerOptions option = new MarkerOptions()  
				.position(point)  
				.icon(bitmap);  
		if(marker!=null){
			marker.remove();
		}
		//在地图上添加Marker，并显示  
		marker=(Marker) mBaidumap.addOverlay(option);
//		Bundle bundle=new Bundle();
//		bundle.putSerializable("locationInfo", locationInfo);
//		marker.setExtraInfo(bundle);
	}

	Runnable runnable=new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			RequestGrabLocation requestGrabLoc=new RequestGrabLocation(deviceId, uuid, order.getUserId());
			new GetGrabLocation(OrderDetailActivity.this, handler, requestGrabLoc).start();
			handler.postDelayed(runnable, 60000);
		}
	};
	/**
	 * 发起路线规划搜索示例
	 *
	 */
	private void searchLines(){
		// 设置起终点信息，对于tranist search 来说，城市名无意义
		//				PlanNode stNode = PlanNode.withCityNameAndPlaceName("北京", "龙泽");
		//				PlanNode enNode = PlanNode.withCityNameAndPlaceName("北京", "西单");
		route = null;
		//		LatLng end = new LatLng(39.648593, 116.434307);  
		//		LatLng start = new LatLng(31.21316849046321, 121.51698589324951);

		float startLatitude,startLongitude;

		startLatitude=Float.parseFloat(order.getGrabLatitude());
		startLongitude=Float.parseFloat(order.getGrabLongitude());

		float endLatitude=Float.parseFloat(order.getLatitude());
		float endLongitude=Float.parseFloat(order.getLongitude());
		LatLng start = new LatLng(startLatitude, startLongitude);  
		LatLng end = new LatLng(endLatitude, endLongitude); 
		PlanNode startNode=PlanNode.withLocation(start);
		PlanNode endNode=PlanNode.withLocation(end);

		mSearch.drivingSearch((new DrivingRoutePlanOption())
				.from(startNode).to(endNode));

	}

	@Override
	public void onGetBikingRouteResult(BikingRouteResult arg0) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onGetDrivingRouteResult(DrivingRouteResult resul) {
		// TODO Auto-generated method stub
		if (resul == null) {  
			Toast.makeText(OrderDetailActivity.this, "抱歉，未找到结果", Toast.LENGTH_LONG).show();  
			return;  
		}  
		// 叠加路线到地图显示，此处仅展示一个方案作为示例  
		if (resul.error == SearchResult.ERRORNO.NO_ERROR) {
			//			route = resul.getRouteLines().get(0);
			//            DrivingRouteOverlay overlay = new DrivingRouteOverlay(mBaidumap);
			//            routeOverlay = overlay;
			//            mBaidumap.setOnMarkerClickListener(overlay);
			//            overlay.setData(resul.getRouteLines().get(0));
			//            overlay.addToMap();
			//            overlay.zoomToSpan();

			if (resul.getRouteLines().size() > 1 ) {
				nowResultd = resul;

				route = nowResultd.getRouteLines().get(0);
				DrivingRouteOverlay overlay = new DrivingRouteOverlay(mBaidumap);
				mBaidumap.setOnMarkerClickListener(overlay);
				overlay.setData(nowResultd.getRouteLines().get(0));
				overlay.addToMap();
				overlay.zoomToSpan();
				new VoiceUtil("路线规划成功", OrderDetailActivity.this).VoicePlay();
			} else if ( resul.getRouteLines().size() == 1 ) {
				route = resul.getRouteLines().get(0);
				DrivingRouteOverlay overlay = new DrivingRouteOverlay(mBaidumap);
				mBaidumap.setOnMarkerClickListener(overlay);
				overlay.setData(resul.getRouteLines().get(0));
				overlay.addToMap();
				overlay.zoomToSpan();
				new VoiceUtil("路线规划成功", OrderDetailActivity.this).VoicePlay();

			}

		}
	}
	@Override
	public void onGetTransitRouteResult(TransitRouteResult arg0) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onGetWalkingRouteResult(WalkingRouteResult arg0) {
		// TODO Auto-generated method stub

	}

	// 创建地图Activity，管理地图生命周期  
	@Override    
	protected void onDestroy() {    
		super.onDestroy();    
		//在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理    
		mMapView.onDestroy();    
		mSearch.destroy();
		geoCoder.destroy();
		handler.removeCallbacks(runnable);
		new VoiceUtil("", OrderDetailActivity.this).VoiceStop();
	}    
	@Override    
	protected void onResume() {    
		super.onResume();    
		//在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理    
		mMapView.onResume();    
	}    
	@Override    
	protected void onPause() {    
		super.onPause();    
		//在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理    
		mMapView.onPause();    
	}

	@Override
	public void onGetGeoCodeResult(GeoCodeResult arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
		// TODO Auto-generated method stub
		if (arg0 == null || arg0.error != SearchResult.ERRORNO.NO_ERROR) {  
			Toast.makeText(this, "抱歉，未能找到结果", Toast.LENGTH_LONG)  
			.show();  
			return;  
		}
		//		startPoint.setText(arg0.getAddress());
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.taskDetail:

			taskPop=new TaskOperationPopwindow(OrderDetailActivity.this, new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					RequestcaseCancel caseCancel=new RequestcaseCancel(deviceId, uuid, order.getCaseNumber(), order.getId());
					new CaseCancelThread(OrderDetailActivity.this, handler, caseCancel).start();
					taskPop.dismiss();
				}
			}, new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					RequestcaseCancel caseStop=new RequestcaseCancel(deviceId, uuid, order.getCaseNumber(), order.getId());
					new CaseStopThread(OrderDetailActivity.this, handler, caseStop).start();
					taskPop.dismiss();
				}
			},
					new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					progressdialog=ProgressDialog.show(OrderDetailActivity.this, null, "重新播报，请稍等…", false, false);

					RequestReBroadcast reBroadcast=new RequestReBroadcast(deviceId, uuid, order.getId(), order.getCaseNumber());
					Log.i("wl", "按件重新播报请求"+reBroadcast.toString());
					new ReBroadcastThread(OrderDetailActivity.this, handler, reBroadcast).start();
					taskPop.dismiss();
				}
			},caseState);
			// 设置ppw显示的位置
			taskPop.showAtLocation(OrderDetailActivity.this
					.findViewById(R.id.mMapView), Gravity.CENTER
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;

		case R.id.returnBack:
			finish();
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onMarkerClick(Marker marker) {
		// TODO Auto-generated method stub
		showLocation(marker);
		return false;
	} 

	private InfoWindow mInfoWindow;
	private void showLocation(final Marker marker) {  //显示气泡
		// 创建InfoWindow展示的view

		LatLng pt = null;
		double latitude, longitude;
		latitude = marker.getPosition().latitude;
		longitude = marker.getPosition().longitude;
		
		Bundle bundle=marker.getExtraInfo();
		if(bundle==null){
			return;
		}
		EsUserInfo userInfo=(EsUserInfo) bundle.getSerializable("userInfo");

		View view = LayoutInflater.from(this).inflate(R.layout.balloon_overlay, null); //自定义气泡形状
		TextView textTittle = (TextView) view.findViewById(R.id.balloon_item_title);
//		TextView textContent=(TextView) view.findViewById(R.id.balloon_item_snippet);
		textTittle.setText("查勘员:"+userInfo.getRealName());
//		textContent.setText("内容：某某地址"+locationInfo.getUpdateTime());

		// 定义用于显示该InfoWindow的坐标点
		pt = new LatLng(latitude , longitude );
		
		// 创建InfoWindow
//		mInfoWindow=new InfoWindow(view, pt, -30);
		
		//将布局转化为图片控件
		BitmapDescriptor bitmap = BitmapDescriptorFactory.fromView(view);
		
		// 创建InfoWindow的点击事件监听者
		OnInfoWindowClickListener listener = new OnInfoWindowClickListener() {
			public void onInfoWindowClick() {
				mBaidumap.hideInfoWindow();//影藏气泡

			}
		};
		
		mInfoWindow = new InfoWindow(bitmap, pt, -30, listener);
		mBaidumap.showInfoWindow(mInfoWindow); //显示气泡
		bitmap.recycle();
	}


}
